package com.swak.vertx.config;

import org.springframework.beans.factory.FactoryBean;

import com.swak.vertx.proxy.ProxyFactory;

/**
 * 依赖配置
 * 
 * @bug : 使用 implements FactoryBean<T> 会导致 T 在spring 中有多个实例， 如果是接口没问题 这个改进，与Tcc
 *      有关，先去掉，后续测试Tcc时更新方案；
 *
 * @author: lifeng
 * @date: 2020/3/29 19:10
 */
public class ReferenceBean<T> implements FactoryBean<T> {

	private Class<?> type;
	private Object refer;
	private String address;

	/**
	 * 在发起者线程中执行回调
	 */
	private boolean callBackInSourceContext;

	public Class<?> getType() {
		return type;
	}

	public void setType(Class<?> type) {
		this.type = type;
	}

	public Object getRefer() {
		return refer;
	}

	public void setRefer(Object refer) {
		this.refer = refer;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public boolean isCallBackInSourceContext() {
		return callBackInSourceContext;
	}

	public void setCallBackInSourceContext(boolean callBackInSourceContext) {
		this.callBackInSourceContext = callBackInSourceContext;
	}

	/**
	 * 获得代理对象,可以切换为其他代理实现
	 *
	 * @param vertx vertx代理
	 * @return 代理对象
	 */
	public Object get() {
		if (refer == null) {
			refer = ProxyFactory.newProxy(type, address, callBackInSourceContext);
		}
		return refer;
	}

	@Override
	@SuppressWarnings("unchecked")
	public T getObject() throws Exception {
		return (T) this.get();
	}

	@Override
	public Class<?> getObjectType() {
		return type.isInterface() ? type : ReferenceBean.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
}